package org.yan.stock.server.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * @Func 
 * @author yanxuxin_sz
 * @Date 2010-12-26
 */
public abstract class StrUtil {
	
	public static String capitalize(CharSequence cs) {
		if (cs == null) {
			return null;
		}
		int strLen;
		if ((strLen = cs.length()) == 0) {
			return cs.toString();
		}
		return new StringBuilder(strLen)
				.append(Character.toTitleCase(cs.charAt(0)))
				.append(cs.subSequence(1, strLen)).toString();
	}
	
	/**
	 * Convert string collection to a string. 
	 * @param strColl
	 * @param separator
	 * @return
	 */
	public static String coll2String(Collection<String> strColl, String separator) {
		if(strColl == null) {
			return null;
		}
		StringBuilder sb = new StringBuilder("");
		boolean isHead = true;
		for(String str : strColl) {
			if(isHead) {
				isHead = false;
			}
			else {
				sb.append(separator);
			}
			sb.append(str);
		}
		
		return sb.toString();
	}

	/**
	 * Convert object's parameter collection to a string.
	 * @param <T>
	 * @param objColl
	 * @param propName --The first letter must be upcase. 
	 * @param separator
	 * @return
	 */
	public static <T> String coll2String(Collection<T> objColl, String propName, String separator) {
		if(objColl == null) {
			return null;
		}
		List<String> strList = new ArrayList<String>(objColl.size());
		boolean isFirst = true;
		Class<?> objClass = null;
		Method method = null;
		for(T t : objColl) {
			if(isFirst) {
				isFirst = false;
				objClass = t.getClass();
				try {
					method = objClass.getDeclaredMethod("get"+propName, new Class[0]);
					method.setAccessible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			try {
				strList.add((String)method.invoke(t, new Object[0]));
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		
		return coll2String(strList, separator);
	}
	
	/**
	 * Convert object's parameter array to a string.
	 * @param <T>
	 * @param tArr
	 * @param propName --The first letter must be upcase. 
	 * @param separator
	 * @return
	 */
	public static <T> String arr2String(T[] tArr, String propName, String separator) {
		if(tArr == null) {
			return null;
		}
		List<String> strList = new ArrayList<String>(tArr.length);
		boolean isFirst = true;
		Class<?> objClass = null;
		Method method = null;
		for(T t : tArr) {
			if(isFirst) {
				isFirst = false;
				objClass = t.getClass();
				try {
					method = objClass.getDeclaredMethod("get"+StrUtil.capitalize(propName), new Class[0]);
					method.setAccessible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			try {
				strList.add((String)method.invoke(t, new Object[0]));
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		
		return coll2String(strList, separator);
	}
}
